package com.kgc.crowd.distributioncrowdwebui.controller;

import com.kgc.crowd.distributioncrowdcommon.VO.*;
import com.kgc.crowd.distributioncrowdcommon.api.MemberMangerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.api.ProjectMangerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.pojo.MemberLaunchInfoPO;
import com.kgc.crowd.distributioncrowdcommon.pojo.ResultEntity;
import com.kgc.crowd.distributioncrowdcommon.pojo.TypePO;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdConstant;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdUtils;
import com.kgc.crowd.distributioncrowdcommon.util.UploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/project/manager")
@Controller
public class ProjectController {
    @Value("${endpoint}")
    private String endpoint;
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${accessKeySecret}")
    private String accessKeySecret;
    @Value("${bucketName}")
    private String bucketName;
    @Value("${headPicturefolderName}")
    private String headPicturefolderName;
    @Value("${detailPicturefolderName}")
    private String detailPicturefolderName;
    @Value("${domain}")
    private String domain;
    @Value("${returnFolderName}")
    private String returnFolderName;

    @Resource
    ProjectMangerRemoteService projectMangerRemoteService;

    @Resource
    MemberMangerRemoteService memberMangerRemoteService;

    @RequestMapping("/start")
    public String toStart() {
        return "start";
    }

    @RequestMapping("/agree/protocol")
    public String agreeprotocol(HttpSession session, Model model) {
        //获取登陆状态
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj == null) {
            return "redirect:/to/login.html";
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) obj;
        String token = memberSignSuccessVO.getToken();
        //加载分类信息
        ResultEntity<List<TypePO>> typePoResultEntity = projectMangerRemoteService.selectAllType();
        model.addAttribute(CrowdConstant.ATTR_NAME_TYPEPO_LIST, typePoResultEntity.getData());
        //加载标签信息
        ResultEntity<List<TagVO>> tagResultEntity = projectMangerRemoteService.selectAllTag();
        model.addAttribute(CrowdConstant.ATTR_NAME_TAG_LIST, tagResultEntity.getData());
        //回显发起人信息
        ResultEntity<MemberLaunchInfoPO> memberLaunchInfoPOResultEntity = memberMangerRemoteService.retrieveMemberLaunchInfoByMemberToken(token);
        model.addAttribute(CrowdConstant.ATTR_NAME_MEMBERLAUNCHINFO, memberLaunchInfoPOResultEntity.getData());
        //初始化ProjectVO
        ResultEntity<ProjectVO> projectVOResultEntity = projectMangerRemoteService.initCreation(token);
        if (projectVOResultEntity.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, projectVOResultEntity.getMessage());
            return "redirect:/project/manager/start";
        }
        //把ProjectVO存入session
        session.setAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT, projectVOResultEntity.getData());
        return "start-step-1";
    }

    @RequestMapping("/upload/head/picture")
    @ResponseBody
    public ResultEntity<String> uploadJeadPicture(MultipartFile headerPicture, HttpSession session) throws IOException {
        //判断是否登录
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) obj;
        String memberSignToken = memberSignSuccessVO.getToken();
        Object obj2 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2 == null) {
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        ProjectVO projectVO = (ProjectVO) obj2;
        String projectTempToken = projectVO.getProjectTempToken();
        //判断是否选择文件
        if (headerPicture == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        //把文件对象转成文件流
        InputStream inputStream = headerPicture.getInputStream();
        //获取旧文件名
        String originalFilename = headerPicture.getOriginalFilename();
        //生成新的文件名
        String fileName = UploadUtil.generateFileName(originalFilename);
        //文件上传
        UploadUtil.uploadSingFile(endpoint, accessKeyId, accessKeySecret, fileName, headPicturefolderName, bucketName, inputStream);
        //保存头图路径到redis
        String headPicturePath = domain + "/" + headPicturefolderName + "/" + fileName;
        ResultEntity<String> resultEntity = projectMangerRemoteService.saveHeadPicturePath(memberSignToken, projectTempToken, headPicturePath);
        return resultEntity;
    }

    @RequestMapping("/upload/detail/picture")
    @ResponseBody
    public ResultEntity<String> uploadDetailPicture(HttpSession session,
                                                    @RequestParam("detailPicture") List<MultipartFile> detailPictureList) throws IOException {
        //判断是否登录
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) obj;
        String memberSignToken = memberSignSuccessVO.getToken();
        Object obj2 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2 == null) {
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        ProjectVO projectVO = (ProjectVO) obj2;
        String projectTempToken = projectVO.getProjectTempToken();
        //验证集合是否为空
        if (CrowdUtils.collectionEffectiveCheck(detailPictureList) == false) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        //保存详情图片上传完成后的路径
        List<String> detailPicturePathList = new ArrayList<>();
        //实现文件上传
        for (MultipartFile multipartFile : detailPictureList) {
            boolean empty = multipartFile.isEmpty();
            if (empty) {
                continue;
            }
            //把文件对象转成文件流
            InputStream inputStream = multipartFile.getInputStream();
            //获取旧文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //生成新的文件名
            String fileName = UploadUtil.generateFileName(originalFilename);
            //文件上传
            UploadUtil.uploadSingFile(endpoint, accessKeyId, accessKeySecret, fileName, detailPicturefolderName, bucketName, inputStream);
            //保存详情图路径到redis
            String detailPicturePath = domain + "/" + headPicturefolderName + "/" + fileName;
            detailPicturePathList.add(detailPicturePath);
        }
        ResultEntity<String> resultEntity = projectMangerRemoteService.saveDetailPicturePathList(memberSignToken, projectTempToken, detailPicturePathList);
        return resultEntity;
    }

    @RequestMapping("/save/project/information")
    @ResponseBody
    public ResultEntity<String> saveProjectInformation(ProjectVO projectVO, HttpSession session) {
        MemberSignSuccessVO signVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (signVO == null) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        projectVO.setMemberSignToken(signVO.getToken());
        ProjectVO project = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        projectVO.setProjectTempToken(project.getProjectTempToken());
        System.out.println(projectVO.toString());
        ResultEntity<String> resultEntity = projectMangerRemoteService.saveProjectInformation(projectVO);
        return resultEntity;

    }

    @RequestMapping("/to/project/return")
    public String tostartstep2() {
        return "start-step-2";
    }

    @RequestMapping("/save/return/vo")
    public String saveReturnVO(ReturnVO returnVO,
                               @RequestParam("describPic") MultipartFile describPic,
                               Model model,
                               HttpSession session) throws IOException {
        //验证是否登录
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) obj;
        String memberSignToken = memberSignSuccessVO.getToken();

        Object obj2 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2 == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "请同意协议");
            return "start";
        }
        ProjectVO projectVO = (ProjectVO) obj2;
        String projectTempToken = projectVO.getProjectTempToken();
        //验证是否选择文件
        if (describPic == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_NO_FILE);
            return "start-step-2";
        }
        //获取旧的文件名生成新的文件名
        String originalFilename = describPic.getOriginalFilename();
        String fileName = UploadUtil.generateFileName(originalFilename);
        //把文件对象换成文件流
        InputStream inputStream = describPic.getInputStream();
        //文件上传
        UploadUtil.uploadSingFile(endpoint, accessKeyId, accessKeySecret, fileName, returnFolderName, bucketName, inputStream);
        returnVO.setDescribPicPath(domain + "/" + returnFolderName + "/" + fileName);

        returnVO.setMemberSignToken(memberSignToken);
        returnVO.setProjectTempToken(projectTempToken);
        ResultEntity<String> resultEntity = projectMangerRemoteService.saveReturnVO(returnVO);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "start-step-2";
        }
        return "start-step-3";
    }

    @RequestMapping("/save/member/confirm/info/vo")
    public String savememberConfirmInfo(MemberConfirmInfoVO memberConfirmInfoVO, HttpSession session, Model model) {
        //验证是否登录
        Object obj = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "login";
        }
        MemberSignSuccessVO memberSignSuccessVO = (MemberSignSuccessVO) obj;
        String memberSignToken = memberSignSuccessVO.getToken();

        Object obj2 = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2 == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "请同意协议");
            return "start";
        }
        ProjectVO projectVO = (ProjectVO) obj2;
        String projectTempToken = projectVO.getProjectTempToken();
        memberConfirmInfoVO.setMemberSignToken(memberSignToken);
        memberConfirmInfoVO.setProjectTempToken(projectTempToken);
        ResultEntity<String> resultEntity = projectMangerRemoteService.saveMemberConfirmInfoVO(memberConfirmInfoVO);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "start-step-3";
        }
        //保存到数据库
        ResultEntity<String> resultEntity1 = projectMangerRemoteService.saveWholeProject(memberSignToken, projectTempToken);
        if (resultEntity1.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,resultEntity1.getMessage());
            return "start-step-3";
        }
        return "start-step-4";
    }

}
